<?php
namespace app\admin\controller;
use app\admin\model\ModuleStoreModel;
use app\admin\model\ModulePluginModel;
use think\Model;
use think\Db;
use app\admin\model\UserModel;
use app\admin\model\ModuleResourceModel;
use cmf\controller\AdminBaseController;

class ModuleManageController extends AdminBaseController
{
	public function index()
	{
		$param = $this->request->param();
		$search = [
			'mid' => isset( $param [ 'mid' ] ) ? $param [ 'mid' ] : '',
		];
		$list = ModuleStoreModel::where( 'version' , 'B' )->order('name');
		
		$all = ModuleStoreModel::where( 'version' , 'B' )->order('name')->select();
		
		if( !empty ( $search [ 'mid' ] ) ){
			$list = $list->where( 'id' , $search[ 'mid' ] );
		}
		$list = $list->select();
		
		$this->assign( 'search' , $search );
		$this->assign( 'all' , $all );
		$this->assign( 'list' , $list );
		return $this->fetch();
	}
	
	public function addModule()
	{
		$this->assign( 'category' , $this->getCategory() );
		return $this->fetch();
	}
	
	
	
	public function addModulePost()
	{
		$param =  $this->request->param();
		//dump( $param );exit;
		$rule = [
			'name' => 'require|alpha',
			'title' => 'require',
			'category' => 'require'
		];
		$msg = [
			'name.require' => '标识不能为空',
			'name.alpha' => '标识只能是英文字母',
			'title.require' => '标题不能为空',
			'category' => '分类不能为空'
		];
		
		$result = new \think\Validate( $rule , $msg )  ;
		if( !$result->check ( $param ) ){
			return api_json_echo( false , $result->getError() , null , 100 );
		}
		$param [ 'name' ] = cmf_parse_name( $param [ 'name' ] , 1 );
		
		$find = ModuleStoreModel::where( [ 'version'=>'B','name'=>$param[ 'name' ]] )->find();
		if( $find ){
			return api_json_echo( false , $param[ 'name' ].'已存在' , null , 101 );
		}
		
		$param [ 'author_id' ] = cmf_get_current_admin_id();
		$param [ 'author' ] = ( new UserModel() )->where( 'id' , $param [ 'author_id' ] )->value( 'user_login' );
		
		$param [ 'version' ] = 'B';
		$param [ 'word' ] = $this->getWordNo( $param [ 'name' ] , $param[ 'title'] );
		
		$param [ 'menu_id' ] = $this->getAdminMenuId( $param [ 'name' ] , $param[ 'title'] );
		
		if( !( new ModuleStoreModel() )->allowField(true)->save( $param ) ){
			return api_json_echo( false , '添加失败' , null , 102 );
		}
		return api_json_echo( true , '添加成功' );
		
		
		
	}
	
	private function getCategory()
	{
		return Model( 'module_category' )->select();
	}
	
	
	private function getWordNo( $name , $title )
	{
		$parentId = DB('word')->where( 'content' , 'THISISMODULEDIR' )->value( 'id' );
		
		$word = [
			'name' => $title,
			'type' => 1,
			'parent_id' => $parentId,
			'content' => 'MODULE_'.strtoupper( $name ),
			'create_time' => time(),
			'create_user' => cmf_get_current_admin_id()
		];
		$where = [
			'content' => 'MODULE_'.strtoupper( $name ),
		];
		$id  = Db('word')->where( 'content' , $word[ 'content' ] )->value( 'id' );
		if( !$id ){
			$id = Db('word')->insertGetId( $word );
		}
		return $id;
		
	}
	
	
	private function getAdminMenuId( $name , $title )
	{	
		$menu = [
			'app' => 'plugin/'.cmf_parse_name( $name , 1 ),
			'parent_id'=>1,
			'type' => 1,
			'status' => 1,
			'controller' => 'AdminIndex',
			'action' => 'index',
			'name' => $title,
			'module_version' => '*B*',
		];
		
		$where= [
			'app' => 'plugin/'.cmf_parse_name( $name , 1 ),
			'controller' => 'AdminIndex',
			'action' => 'index',
		];
		$find = Db('admin_menu')->where( $where )->find( );

		if( !isset( $find [ 'id' ] ) || empty( $find [ 'id' ] ) ){
			$id = DB( 'admin_menu' )->insertGetId( $menu );
		}else{
			$id = $find [ 'id' ];
			$moduleVersion = $find['module_version'].',*B*';
			Db('admin_menu')->where( 'id' , $id )->update( [ 'module_version' => $moduleVersion ] );
		}
		
		return $id;
	}
	
	
	public function del($id)
	{
		$find = ModuleStoreModel::get( $id );
	
		if( !$find ){
			return api_json_echo( false , '数据不存在' );
		}
		//delete menu
		$this->deleteMenu ( $find [ 'menu_id' ] );
		//delete word
		$this->deleteWord( $find[ 'word' ] );
		//delete module
		if( !ModuleStoreModel::destroy( $id ) ){
			return api_json_echo( false , '删除失败' );
		}		
		return api_json_echo( true , '删除成功' );
		
	}
	
	private function deleteMenu( $id ){
		if( $id ){
			Db( 'admin_menu' )->delete( $id );
		}
		
	}
	private function deleteWord( $id ){
		
		//if($id)
		//db( 'word' )->delete( $id );
	}
	
	
	public function editModule( $id )
	{	
		$da = ModuleStoreModel::get( $id );
		
		$category = $this->getCategory();
		
		$this->assign( 'category' , $category );
		$this->assign( 'da' , $da );
		return $this->fetch( );
	}
	
	public function editModulePost()
	{
		$param =  $this->request->param();
		$rule = [
			'id' => 'require',
			'title' => 'require',
			'category' => 'require'
		];
		$msg = [
			'id.require' =>'标识不能为空' ,
			'title.require' => '标题不能为空',
			'category' => '分类不能为空'
		];
		
		$result = new \think\Validate( $rule , $msg )  ;
		if( !$result->check ( $param ) ){
			return api_json_echo( false , $result->getError() , null , 100 );
		}
		
		$update = [
			'id' => $param[ 'id' ],
			'title' => $param[ 'title' ],
			'status' => $param [ 'status' ],
			'describe' => ( !isset( $param [ 'describe' ] ) || empty( $param [ 'describe' ] ) ) ? '无' : $param [ 'describe' ], 
		];
		
		
		
		if( !( new ModuleStoreModel() )->allowField(true)->isUpdate( true )->save( $update ) ){
			return api_json_echo( false , '修改失败' , null , 102 );
		}
		return api_json_echo( true , '修改成功' );
	}
	
	
	public function updates()
	{
		$param = $this->request->param();
		//dump( $param );exit;
		if( !( new ModuleStoreModel() )->allowField(true)->isUpdate( true )->save( $param ) ){
			return api_json_echo( false , '更新失败' , null , 102 );
		}
		return api_json_echo( true , '更新成功' );
	}
	
	public function uploadres( $id,$type = 1 )
	{
		if( $type ==1 ){
			$type = 'module';
			$find = ModuleStoreModel::get($id);
		}else{
			$type = 'plugin';
			$find = ModulePluginModel::get( $id );
		}
		$name = cmf_parse_name( $find [ 'name' ] );
		$version = $find[ 'version' ];
		
		
		$file = request()->file('file');
		if($file){
			$info = $file->validate(['ext'=>'zip'])->move( ROOT_PATH . 'public' . DS . 'upload'.DS.$type.DS.$name.DS.$version.DS.'resource');
			if($info){
				// 成功上传后 获取上传信息
				// 输出 jpg
				/*echo $info->getExtension();
				// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
				echo $info->getSaveName();
				// 输出 42a79759f284b767dfcb2a0197904287.jpg
				echo $info->getFilename(); */
				$resource = 'upload'.'/'.$type.'/'.$name.'/'.$version.'/resource/'.$info->getSaveName();
				
				if( $type == 'module' ){
					ModuleStoreModel::where( 'id' , $id )->update( [ 'resource'=>$resource ] );
				}else{
					ModulePluginModel::where( 'id' , $id )->update( [ 'resource'=>$resource ] );
				}
				
				$insert = [ 
					'url' => $resource,
					're_id' => $id,
					'type' => ($type=='module')?1:2,
					'author'=>'',
					'author_id'=>'',
					'file_name' => $info->getFilename(),
				];
				ModuleResourceModel::create( $insert );
				return api_json_echo( true , '上传成功' , null , 101 );
			}else{
				// 上传失败获取错误信息
				//echo $file->getError();
				return api_json_echo( false , $file->getError() , null , 101 );
			}
		}
		return api_json_echo( false , '失败' , null , 100 );
	}
	
	
	public function resourcePage( $id , $type )
	{
		$list = ModuleResourceModel::where(['re_id'=>$id , 'type'=>$type])->order('update_time desc')->select();
		$this->assign( 'list' , $list );
		$this->assign( 'id' , $id );
		$this->assign( 'type' , $type );
		return $this->fetch( 'resource' );
	}
	
	public function delresource( $id , $type )
	{
		
		$resource = ModuleResourceModel::where(['id'=>$id])->value('url');
		if( !empty( $resource ) ){
			$path = ROOT_PATH.'public'.DS.str_replace( '/', DS , $resource);
			if( file_exists( $path ) ){
				@unlink( $path );
			}
		}
		$res = ModuleResourceModel::destroy($id);
		if( !$res ){
			return api_json_echo( false , '删除失败' );
		}
		return api_json_echo(true, '删除成功');
	}
	
	public function setMr( $id , $type , $mid )
	{
		//将更新时间设置为当前时间
		$find = ModuleResourceModel::get($id);
		$url = $find[ 'url' ];

		if( $type == 1 ){
			//module
			ModuleStoreModel::where( 'id' , $find['re_id'] )->update( ['resource'=>$url] );
		}else{
			//plugin
			ModulePluginModel::where( 'id' , $find[ 're_id' ])->update( [ 'resource'=>$url ] );
		}
		if(!ModuleResourceModel::where('id',$id)->update( [ 'update_time'=>time()] )){
			return api_json_echo(false , '设置失败' );
		}
		return api_json_echo( true , '设置成功');
	}
	
	public function update()
	{
		$id = input('param.id');
		$remarks = input('param.value');
		if( !ModuleResourceModel::where('id',$id) ->update( [ 'remarks'=>$remarks ] ) ){
			return api_json_echo( false , '保存失败' );
		}
		return api_json_echo( true , '保存成功');
	}
	
	
	
	
	
	
	
	
	
	
	
}